package com.happok.onlineclass.usermanagement.authentication.config;

import cn.hutool.json.JSONObject;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 接口分类                        yapi 分类文件夹
 * 功能说明
 *
 * @author : chenac
 * @module 项目名称/模块名          yapi 项目组/子项目
 * @date : 2021/7/15 10:19
 */
@Component
public class UserAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject(true);

        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
            jsonObject.set("code", "40103");
            jsonObject.set("msg", "用户名或密码错误");
        } else if (e instanceof DisabledException) {
            jsonObject.set("code", "40104");
            jsonObject.set("msg", "账户被禁用");
        } else {
            jsonObject.set("code", "40105");
            jsonObject.set("msg", "登录失败!");
        }
        httpServletResponse.getWriter().write(jsonObject.toString());
        httpServletResponse.flushBuffer();
    }
}